# -*- coding:utf-8 -*-
# @Time : 21-9-2 下午3:26 
# @Author : zdy
# @File : UIMethod.py
# desc:

from UIONH.MethodONH import Ui_Method
from Class.Devices import *
import os, glob
from importQT import *
from Class.CSConfig import *

class UIMethod(QDialog, Ui_Method):
    def __init__(self):
        super(UIMethod, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("方法")
        self.applyResource()
        self.powerModel = QStandardItemModel(self)
        self.purge = "脱气"
        self.wait = "等待"
        self.analyse = "分析"
        self.maxPower = 9000
        self.maxI = 1500
        self.bUpdata = False
        self.cbbType.addItem(self.purge)
        self.cbbType.addItem(self.wait)
        self.cbbType.addItem(self.analyse)
        self.btnSave.clicked.connect(self.saveParams)
        self.setWindowFlags(Qt.WindowCloseButtonHint)
        self.setFixedSize(self.width(), self.height())
        self.btnload.clicked.connect(self.loadMethod)
        self.btndel.clicked.connect(self.delMethod)
        self.spinBoxDecimals.setMaximum(8)
        self.rdbtnPower.toggled.connect(self.rdbtnPower_changed)
        self.loadfilename()
        self.cbName.setEditable(True)
        self.updateParams(device.config)
        self.btnDelRow.clicked.connect(self.btnDelRow_clicked)
        self.btnInsert.clicked.connect(self.btnInsert_clicked)
        self.thermalH = device.config.thermalH
        if not device.analyseStop:
            self.btnSave.setEnabled(False)
            self.btnload.setEnabled(False)

    def loadfilename(self):
        """cbName加载方法名"""
        self.cbName.clear()
        os.chdir(device.configFolder)
        for file in glob.glob("*.bin"):
            name = file.split(".")[0]
            if name != "systemconfig":
                self.cbName.addItem(name)
        self.cbName.setCurrentText(device.config.name)

    def applyResource(self):
        self.setWindowIcon(getIcon())

    def loadMethod(self):
        config = device.getconfig(self.cbName.currentText())
        if config is not None:
            device.config = config
            self.updateParams(device.config)

    def updateParams(self, config):
        self.bUpdata = True
        self.cbName.setCurrentText(config.name)
        self.spinBoxBsaselineV.setValue(config.baselineDeviation)
        self.spinBoxBaselineT.setValue(config.baselineTime)
        self.spinBoxSwitch1.setValue(config.switch1)
        self.dSpinBoxBlank1.setValue(config.blank1)
        self.dSpinBoxBlank2.setValue(config.blank2)
        self.dSpinBoxBlank3.setValue(config.blank3)
        self.spinBoxDecimals.setValue(config.decimals)
        self.chkThermalH.setChecked(config.thermalH)

        self.rdbtnPower.setChecked(config.PIDStyle == 0)
        self.rdbtnI.setChecked(config.PIDStyle == 1)
        self.updatePower(config.powerArray, config.PIDStyle)

        self.chk0.setChecked(config.channels[0].enable)
        self.chk1.setChecked(config.channels[1].enable)
        self.chk2.setChecked(config.channels[2].enable)
        self.chk3.setChecked(config.channels[3].enable)

        self.dSpinBoxPeakratio0.setValue(config.channels[0].ratio)
        self.dSpinBoxPeakratio1.setValue(config.channels[1].ratio)
        self.dSpinBoxPeakratio2.setValue(config.channels[2].ratio)
        self.dSpinBoxPeakratio3.setValue(config.channels[3].ratio)

        self.spinBoxComporator0.setValue(config.channels[0].comporator)
        self.spinBoxComporator1.setValue(config.channels[1].comporator)
        self.spinBoxComporator2.setValue(config.channels[2].comporator)
        self.spinBoxComporator3.setValue(config.channels[3].comporator)

        self.spinBoxDelay0.setValue(config.channels[0].delay)
        self.spinBoxDelay1.setValue(config.channels[1].delay)
        self.spinBoxDelay2.setValue(config.channels[2].delay)
        self.spinBoxDelay3.setValue(config.channels[3].delay)

        self.spinBoxMin0.setValue(config.channels[0].min)
        self.spinBoxMin1.setValue(config.channels[1].min)
        self.spinBoxMin2.setValue(config.channels[2].min)
        self.spinBoxMin3.setValue(config.channels[3].min)

        self.spinBoxMax0.setValue(config.channels[0].max)
        self.spinBoxMax1.setValue(config.channels[1].max)
        self.spinBoxMax2.setValue(config.channels[2].max)
        self.spinBoxMax3.setValue(config.channels[3].max)
        self.bUpdata = False

    def updatePower(self, powerArray, pidtype):
        if pidtype == 0:
            self.spStart.setMaximum(self.maxPower)
            self.spEnd.setMaximum(self.maxPower)
        if pidtype == 1:
            self.spStart.setMaximum(self.maxI)
            self.spEnd.setMaximum(self.maxI)
        self.powerModel.clear()
        self.powerModel.setColumnCount(4)
        self.powerModel.setHorizontalHeaderLabels(["类型", "起始", "结束", "时间"])
        for i, power in enumerate(powerArray):
            type = ""
            if power.type == 0:
                type = self.purge
            if power.type == 1:
                type = self.wait
            if power.type == 2:
                type = self.analyse
            self.powerModel.setItem(i, 0, QStandardItem(type))
            self.powerModel.setItem(i, 1, QStandardItem(str(power.beginpower)))
            self.powerModel.setItem(i, 2, QStandardItem(str(power.endpower)))
            self.powerModel.setItem(i, 3, QStandardItem(str(power.timepower)))
        self.powerModel.dataChanged.connect(self.dataChangedSlot)
        self.tableViewPower.setModel(self.powerModel)
        self.tableViewPower.setItemDelegateForColumn(0, EditDelegate(self))

    def rdbtnPower_changed(self):
        if self.bUpdata:
            return
        else:
            if QMessageBox.Yes == QMessageBox.warning(self, "提示", "确定要切换控制模式吗？", QMessageBox.Yes, QMessageBox.No):
                self.powerModel.clear()
                if self.rdbtnPower.isChecked():
                    powerArray = [Power(0, 4500, 4500, 30), Power(1, 4200, 4200, 45), Power(2, 4200, 4200, 40)]
                    pidType = 0
                else:
                    powerArray = [Power(0, 1100, 1100, 30), Power(1, 1050, 1050, 45), Power(2, 1050, 1050, 40)]
                    pidType = 1
                self.updatePower(powerArray, pidType)
            else:
                self.bUpdata = True
                self.rdbtnPower.setChecked(not self.rdbtnPower.isChecked())
                self.bUpdata = False

    def dataChangedSlot(self, topLeft, bottomRight, roles):
        pass

    def btnDelRow_clicked(self):
        types = []
        rows = self.powerModel.rowCount()
        for i in range(rows):
            types.append(self.powerModel.item(i, 0).data(0))
        model = self.tableViewPower.selectionModel()
        rowIndexs = (model.selectedRows())[::-1]
        for i in rowIndexs:
            types.pop(i.row())
        if self.purge in types and self.wait in types and self.analyse in types:
            for j in rowIndexs:
                self.powerModel.removeRow(j.row())
        else:
            QMessageBox.warning(self,"提示","每个过程必须保留一条数据")

    def btnInsert_clicked(self):
        model = self.tableViewPower.selectionModel()
        rowIndexs = (model.selectedRows())[::-1]
        if len(rowIndexs) ==1:
            index = rowIndexs[0].row()
            current = self.powerModel.item(index,0).data(0)
            currentIndex = 0
            currentIndex1 = 0
            if current == self.wait:
                currentIndex = 1
            if current == self.analyse:
                currentIndex = 2
            if index >0:
                current1 = self.powerModel.item(index-1, 0).data(0)
                if current1 == self.wait:
                    currentIndex1 = 1
                if current1 == self.analyse:
                    currentIndex1 = 2
            else:
                currentIndex1 = currentIndex
            if self.cbbType.currentIndex() <= currentIndex and self.cbbType.currentIndex() >=currentIndex1:
                type = self.cbbType.currentText()
                begin = self.spStart.value()
                end = self.spEnd.value()
                time = self.spTime.value()
                self.powerModel.insertRow(index, QModelIndex())
                item = QStandardItem()
                item.setData(type, Qt.DisplayRole)
                self.powerModel.setItem(index, 0, item)
                item1 = QStandardItem()
                item1.setData(str(begin), Qt.DisplayRole)
                self.powerModel.setItem(index, 1, item1)
                item2 = QStandardItem()
                item2.setData(str(end), Qt.DisplayRole)
                self.powerModel.setItem(index, 2, item2)
                item3 = QStandardItem()
                item3.setData(str(time), Qt.DisplayRole)
                self.powerModel.setItem(index, 3, item3)
            else:
                QMessageBox.warning(self, "提示", "不可插入该位置")
        else:
            QMessageBox.warning(self, "提示", "请选中一行数作为插入位置")

    def saveParams(self):
        config = ONHConfig()
        config.name = self.cbName.currentText()
        config.baselineDeviation = self.spinBoxBsaselineV.value()
        config.baselineTime = self.spinBoxBaselineT.value()
        config.switch1 = self.spinBoxSwitch1.value()
        config.blank1 = self.dSpinBoxBlank1.value()
        config.blank2 = self.dSpinBoxBlank2.value()
        config.blank3 = self.dSpinBoxBlank3.value()
        config.factors[0].blank = config.blank1
        config.factors[1].blank = config.blank1
        config.factors[2].blank = config.blank2
        config.factors[3].blank = config.blank2
        config.decimals = self.spinBoxDecimals.value()
        config.thermalH = self.chkThermalH.isChecked()
        config.PIDStyle = 0 if self.rdbtnPower.isChecked() else 1
        maxValue = self.maxPower if config.PIDStyle == 0 else self.maxI
        powerArray = []
        rows = self.powerModel.rowCount()
        for i in range(rows):
            power = Power()
            power.type = 0
            type = self.powerModel.item(i, 0).data(0)
            if type == self.wait:
                power.type =1
            if type == self.analyse:
                power.type = 2
            try:
                beginpower = (int)(self.powerModel.item(i, 1).data(0))
                if beginpower > maxValue:
                    raise Exception("起始值不可超过"+str(maxValue))
                endpower = (int)(self.powerModel.item(i, 2).data(0))
                if endpower > maxValue:
                    raise Exception("结束值不可超过"+str(maxValue))
                time = (int)(self.powerModel.item(i, 3).data(0))
                if time < 0:
                    raise Exception("时间不可为负值")
            except Exception as err:
                QMessageBox.warning(self, "提示", str(err))
                return
            power.beginpower = beginpower
            power.endpower = endpower
            power.timepower = time
            powerArray.append(power)
        config.powerArray = powerArray

        config.channels[0].enable = self.chk0.checkState() == Qt.Checked
        config.channels[1].enable = self.chk1.checkState() == Qt.Checked
        config.channels[2].enable = self.chk2.checkState() == Qt.Checked
        config.channels[3].enable = self.chk3.checkState() == Qt.Checked

        if config.thermalH:
            if config.channels[0].enable or config.channels[1].enable or config.channels[2].enable:
                QMessageBox.warning(self, "提示", "热导定H模式不支持测量O、N元素"
                                                "")
                return

        config.channels[0].ratio = self.dSpinBoxPeakratio0.value()
        config.channels[1].ratio = self.dSpinBoxPeakratio1.value()
        config.channels[2].ratio = self.dSpinBoxPeakratio2.value()
        config.channels[3].ratio = self.dSpinBoxPeakratio3.value()

        config.channels[0].comporator = self.spinBoxComporator0.value()
        config.channels[1].comporator = self.spinBoxComporator1.value()
        config.channels[2].comporator = self.spinBoxComporator2.value()
        config.channels[3].comporator = self.spinBoxComporator3.value()

        config.channels[0].delay = self.spinBoxDelay0.value()
        config.channels[1].delay = self.spinBoxDelay1.value()
        config.channels[2].delay = self.spinBoxDelay2.value()
        config.channels[3].delay = self.spinBoxDelay3.value()

        config.channels[0].min = self.spinBoxMin0.value()
        config.channels[1].min = self.spinBoxMin1.value()
        config.channels[2].min = self.spinBoxMin2.value()
        config.channels[3].min = self.spinBoxMin3.value()

        config.channels[0].max = self.spinBoxMax0.value()
        config.channels[1].max = self.spinBoxMax1.value()
        config.channels[2].max = self.spinBoxMax2.value()
        config.channels[3].max = self.spinBoxMax3.value()

        device.config = config
        device.deinit()
        self.loadfilename()

    def delMethod(self):
        if self.cbName.currentText() == device.config.name:
            QMessageBox.warning(self,"提示", "不可删除正在使用的方法")
            return
        filepath = os.path.join(device.configFolder, self.cbName.currentText() + ".bin")
        if os.path.exists(filepath):
            os.remove(filepath)
        self.loadfilename()

    def closeEvent(self, event) -> None:
        if self.thermalH != device.config.thermalH:
            #定氢模式切换
            device.switchNH()
            pass


class EditDelegate(QItemDelegate):
    def __init__(self, parent):
        super(EditDelegate, self).__init__(parent)

    def createEditor(self, QWidget, QStyleOptionViewItem, QModelIndex):
        return None
